<?php
$masterView = MasterView::getInstance();
$comparisons = Comparison::getComparisonList($masterView->streamView->model->streamId);
?>
<script src="/js/Desktop/bootstrap-select.min.js"></script>
<script src="/js/Desktop/bootstrap-select.js"></script>
<link href="/css/Desktop/Desktop/bootstrap-select.css" rel="stylesheet"></link>
<link href="/css/Desktop/Desktop/bootstrap-select.min.css" rel="stylesheet"></link>
<div class="content fixed-fluid" style="overflow: scroll; padding-top: 90px; margin-top: 0;padding-right: 20px;">
    <div class="compare-stream-list">
        <div class="stream-block first">
            <h3><?php echo $masterView->streamView->model->name; ?></h3>
        </div>
        <div class="stream-block">
            <select class="stream-select" multiple title="Select a stream">
                <?php
                $streams = Stream::getStreams($masterView->streamView->model->folderId);
                foreach ($streams as $stream) {
                    if ($stream->streamId == $masterView->streamView->model->streamId)
                        continue;
                    echo '<option value="' . base64_encode($stream->streamId) . '">' . $stream->name . '</option>';
                }
                ?>
            </select>
        </div>
    </div>
    <div class="main-content">
        <?php
        ?>
        <div class="metrics-container skip-loading-animation" style="margin-bottom: 140px;">
            <?php include "SOVHTML.php"; ?>
            <?php include "TrendlineHTML.php"; ?>
            <?php include "SentimentHTML.php" ?>
        </div>
    </div>
</div>
<script>
    /**
     * sov loader
     */
    $(document).ready(function() {
        $('.stream-select').selectpicker({
            'selectedText': 'cat'
        });
        var params = window.location.href.split('#')[1].split('/');
        var streamId1 = params[1];
        var streamIds = [];
        for (i = 2; i < params.length; i++) {
            streamIds.push(params[i]);
            var options = $('select.stream-select option');
            for (j = 0; j < options.length; j++) {
                if (options[j].value == params[i]) {
                    $('div.stream-select .dropdown-menu li')[j].className = "selected";
                }
            }
        }
        $('.stream-select').selectpicker('val', streamIds);
        setTimeout(function() {
            applyFilter();
        }, 500);
        var url = "#compare/" + streamId1 + '/' + streamIds.join('/');
        $('#compare-link-widget a').attr('href', url);
    });

    var sov, SOVRequest;
    function loadSOV(reload) {
        $('.sov-loading').fadeIn(100);
        $('#sov-notice').fadeOut(100);
        $('#sov1, #sov2').hide();
        var streamId1 = window.location.href.split('#')[1].split('/')[1];
        var streamIds = $('.stream-select').val();
        var dateFrom = $('#from').datepicker().val().replace(/\//g, '-');
        var dateTo = $('#to').datepicker().val().replace(/\//g, '-');

        var sentiment = $('#sentiment-filter-widget a.selected').attr('data-value');
        if ($('#sentiment-filter-widget a.selected').length == 0)
            sentiment = 0;
        var language = $('#language-filter-widget').find('a').attr('data-value');
        var type = $('#platform-filter-widget').find('a').attr('data-value');
        var tag = $('#tag-filter-widget').find('a').attr('data-value');
        if (reload) {
            sov = undefined;
            if (SOVRequest !== undefined)
                SOVRequest.abort();
            SOVRequest = $.post('/ws/comparesov/' + streamId1 + '/' + streamIds + '/' + '0' + '/' + dateFrom + '/' + dateTo + '/' + language + '/' + type + '/' + tag + '/' + sentiment, loadSOV_complete);
        }
        else {
            if (SOVRequest.readyState == 4)
                loadSOV_complete();
        }
    }

    function loadSOV_complete(data) {
        if (data == '"Your query has no result! Try again!"') {
            $('#sov1, #sov2').hide();
            $('#sov-notice h5').html('NOT ENOUGH DATA TO SHOW. PLEASE TRY AGAIN LATER.');
            $('#sov-notice').fadeIn(100);
            $('.sov-loading').fadeOut(100);
            return;
        }
        if (data !== undefined)
            sov = JSON.parse(data);
        if (data === undefined && sov === undefined) {
            $('#sov1, #sov2').hide();
            $('#sov-notice h5').html('PLEASE SELECT A STREAM TO COMPARE.');
            $('#sov-notice').fadeIn(100);
            $('.sov-loading').fadeOut(100);
            return;
        }
        $('#sov1, #sov2').show();
        $('.sov-loading').fadeOut(100);
        var categories = new Array();
        var series = new Array();
        var typeOfChart = $('#sov-mentions-widget .hourly-filter-wrapper li.selected').text();
        switch (typeOfChart) {
            case "Total":
                var curStreamName = $('.compare-stream-list .stream-block:first-child').text().trim();
                for (i = 0; i < sov.total.data.length; i++) {
                    if (sov.total.name[i] !== curStreamName)
                        series[i] = {name: sov.total.name[i], y: sov.total.data[i]};
                    else
                        series[i] = {name: sov.total.name[i], y: sov.total.data[i], sliced: true, selected: true};
                }
                categories = sov.total.name;
                $(function() {
                    if ($('#sov2').length == 0)
                        return;
                    $('#sov2').highcharts({
                        chart: {
                            plotBackgroundColor: null,
                            plotBorderWidth: null,
                            plotShadow: false
                        },
                        title: {
                            text: null
                        },
                        tooltip: {
                            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: true,
                                    color: '#000000',
                                    connectorColor: '#000000',
                                    format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                                }
                            }
                        },
                        legend: {
                            borderWidth: 0,
                        },
                        series: [{
                                type: 'pie',
                                name: 'Number of mention',
                                data: series,
                                events: {click: function(e) {
                                        var streamName = e.point.name.trim();
                                        $('.stream-select option').each(function() {
                                            if ($(this).text().trim() === streamName) {
                                                window.location.href = '/#stream/' + $(this).attr('value');
                                            }
                                        });
                                    }}
                            }]
                    });
                });
                categories = [''];
                for (i = 0; i < sov.total.data.length; i++) {
                    series[i] = {name: sov.total.name[i], data: [sov.total.data[i]]};
                }
                $('#sov1').parent().css('width', '45%');
                break;
            case "Monthly":
                categories = sov[0].monthly.name;
                for (var i = 0; i < count(sov) - 1; i++) {
                    series[i] = {name: sov[i].stream.name, data: sov[i].monthly.data};
                }
                $('#sov1').parent().css('width', '96%');
                break;
            case "Weekly":
                categories = sov[0].weekly.date;
                for (var i = 0; i < count(sov) - 1; i++) {
                    series[i] = {name: sov[i].stream.name, data: sov[i].weekly.data};
                }
                $('#sov1').parent().css('width', '96%');
                break;
            case "Daily":
                categories = sov[0].daily.date;
                for (var i = 0; i < count(sov) - 1; i++) {
                    series[i] = {name: sov[i].stream.name, data: sov[i].daily.data};
                }
                $('#sov1').parent().css('width', '96%');
                break;
        }
        $(function() {
            if ($('#sov1').length == 0)
                return;
            $('#sov1').highcharts({
                chart: {
                    type: 'column'
                },
                title: {
                    text: ''
                },
                xAxis: {
                    categories: categories
                },
                yAxis: {
                    min: 0,
                    minTickInterval: 1,
                    gridLineWidth: 0,
                    title: {
                        text: '',
                        align: 'high'
                    },
                    labels: {
                        overflow: 'justify',
                        enabled: true
                    }
                },
                tooltip: {
                    formatter: function() {
                        return '<b>' + this.series.name + '</b><br/>Number of mention: ' + this.y;
                    }
                },
                plotOptions: {
                    column: {
                        dataLabels: {
                            enabled: false
                        }
                    }
                },
                legend: {
                    borderWidth: 0,
                },
                credits: {
                    enabled: false
                },
                series: series
            });
        });
    }
    var TrendRequest, trend;
    function loadTrend(reload) {
        $('.trend-loading').fadeIn(100);
        $('#trend-notice').fadeOut(100);
        $('#widget-trend').hide();
        var streamId1 = window.location.href.split('#')[1].split('/')[1];
        var streamId2 = $('.stream-select').first().val();
        var streamId3 = $('.stream-select').last().val();
        var dateFrom = $('#from').datepicker().val().replace(/\//g, '-');
        var dateTo = $('#to').datepicker().val().replace(/\//g, '-');

        var sentiment = $('#sentiment-filter-widget a.selected').attr('data-value');
        if ($('#sentiment-filter-widget a.selected').length == 0)
            sentiment = 0;
        var language = $('#language-filter-widget').find('a').attr('data-value');
        var type = $('#platform-filter-widget').find('a').attr('data-value');
        var tag = $('#tag-filter-widget').find('a').attr('data-value');
        if (reload) {
            trend = undefined;
            if (TrendRequest !== undefined)
                TrendRequest.abort();
            TrendRequest = $.post('/ws/comparetrend/' + streamId1 + '/' + streamId2 + '/' + streamId3 + '/' + dateFrom + '/' + dateTo + '/' + language + '/' + type + '/' + tag + '/' + sentiment, loadTrend_complete);
        }
        else
            if (TrendRequest.readyState == 4)
                loadTrend_complete();
    }

    function loadTrend_complete(data) {
        if (data == '"Your query has no result! Try again!"') {
            $('#widget-trend').hide();
            $('#trend-notice h5').html('NOT ENOUGH DATA TO SHOW. PLEASE TRY AGAIN LATER.');
            $('#trend-notice').fadeIn(100);
            $('.trend-loading').fadeOut(100);
            return;
        }
        if (data !== undefined)
            trend = JSON.parse(data);
        if (data === undefined && trend === undefined) {
            $('#widget-trend').hide();
            $('#trend-notice h5').html('PLEASE SELECT A STREAM TO COMPARE.');
            $('#trend-notice').fadeIn(100);
            $('.trend-loading').fadeOut(100);
            return;
        }
        $('#widget-trend').show();
        $('.trend-loading').fadeOut(100);
        var categories = new Array();
        var series = new Array();
        var typeOfChart = $('#trend-mentions-widget .hourly-filter-wrapper li.selected').text();
        switch (typeOfChart) {
            case "Daily":
                categories = trend[0].daily.date;
                for (i = 0; i < count(trend); i++) {
                    series[i] = {name: trend[i].stream.name, data: trend[i].daily.data};
                }
                $(function() {
                    if ($('#widget-trend').length == 0)
                        return;
                    $('#widget-trend').highcharts({
                        chart: {
                            type: 'spline',
                            spacingBottom: 0
                        },
                        title: {
                            text: '',
                            x: -20 //center
                        },
                        xAxis: {
                            categories: categories
                        },
                        yAxis: {
                            title: {
                                text: null
                            },
                            min: 0,
                            plotLines: [{
                                    value: 0,
                                    width: 1,
                                    color: '#808080',
                                }],
                            gridLineWidth: 0,
                            labels: {
                                formatter: function() {
                                    return this.value / 1000 + 'k';
                                }
                            },
                        },
                        tooltip: {
                            formatter: function() {
                                return '<b>' + this.series.name + '</b><br/>' +
                                        this.x + ': ' + this.y;
                            }
                        },
                        legend: {
                            borderWidth: 0,
                        },
                        plotOptions: {
                            series: {
                                marker: {
                                    fillColor: 'transparent',
                                    lineWidth: 0,
                                    fillOpacity: 0.1,
                                    lineColor: 'transparent', // inherit from series
                                    states: {
                                        hover: {
                                            lineWidth: 1,
                                            radius: 4,
                                            lineColor: '#EEE',
                                            fillColor: '#FFF'
                                        }
                                    }
                                },
                                fillOpacity: 0.2,
                            }},
                        series: series
                    });
                });
                break;
            case "Monthly":
                if (trend[0].monthly.name === 1) {
                    $('#widget-trend').hide();
                    $('#trend-notice h5').html('NOT ENOUGH DATA TO SHOW. PLEASE TRY AGAIN LATER.');
                    $('#trend-notice').fadeIn(100);
                    $('.trend-loading').fadeOut(100);
                    break;
                }
                categories = trend[0].monthly.name;
                for (i = 0; i < count(trend); i++) {
                    series[i] = {name: trend[i].stream.name, data: trend[i].monthly.data};
                }
                $(function() {
                    if ($('#widget-trend').length == 0)
                        return;
                    $('#widget-trend').highcharts({
                        chart: {
                            type: 'spline',
                            spacingBottom: 0
                        },
                        title: {
                            text: '',
                            x: -20 //center
                        },
                        xAxis: {
                            categories: categories
                        },
                        yAxis: {
                            title: {
                                text: 'Mention'
                            },
                            min: 0,
                            plotLines: [{
                                    value: 0,
                                    width: 1,
                                    color: '#808080',
                                }],
                            gridLineWidth: 0,
                            labels: {
                                formatter: function() {
                                    return this.value / 1000 + 'k';
                                }
                            },
                        },
                        tooltip: {
                            formatter: function() {
                                return '<b>' + this.series.name + '</b><br/>' +
                                        this.x + ': ' + this.y;
                            }
                        },
                        legend: {
                            layout: 'vertical',
                            align: 'right',
                            verticalAlign: 'middle',
                            borderWidth: 0,
                        },
                        plotOptions: {
                            series: {
                                marker: {
                                    fillColor: 'transparent',
                                    lineWidth: 0,
                                    fillOpacity: 0.1,
                                    lineColor: 'transparent', // inherit from series
                                    states: {
                                        hover: {
                                            lineWidth: 1,
                                            radius: 4,
                                            lineColor: '#EEE',
                                            fillColor: '#FFF'
                                        }
                                    }
                                },
                                fillOpacity: 0.2,
                            }},
                        series: series
                    });
                });
                break;
        }
    }

    var sentimentData, sentimentRequest;
    function loadSentiment(reload) {
        $('.sentiment-loading').fadeIn(100);
        $('#sentiment-notice').fadeOut(100);
        $('#sentiment1, #sentiment2, #sentiment3').hide();
        $('#sentiment1, #sentiment2, #sentiment3').html('');
        var streamId1 = window.location.href.split('#')[1].split('/')[1];
        var streamId2 = $('.stream-select').first().val();
        var streamId3 = $('.stream-select').last().val();
        var dateFrom = $('#from').datepicker().val().replace(/\//g, '-');
        var dateTo = $('#to').datepicker().val().replace(/\//g, '-');

        var sentiment = $('#sentiment-filter-widget a.selected').attr('data-value');
        if ($('#sentiment-filter-widget a.selected').length == 0)
            sentiment = 0;
        var language = $('#language-filter-widget').find('a').attr('data-value');
        var type = $('#platform-filter-widget').find('a').attr('data-value');
        var tag = $('#tag-filter-widget').find('a').attr('data-value');
        if (reload) {
            if (sentimentRequest !== undefined)
                sentimentRequest.abort();
            sentimentRequest = $.post('/ws/comparesentiment/' + streamId1 + '/' + streamId2 + '/' + streamId3 + '/' + dateFrom + '/' + dateTo + '/' + language + '/' + type + '/' + tag + '/' + sentiment, loadSentiment_complete);
        }
        else
            loadTrend_complete();
    }

    function loadSentiment_complete(data) {
        if (data == '"Your query has no result! Try again!"') {
            $('#sentiment1, #sentiment2, #sentiment3').hide();
            $('#sentiment-notice h5').html('NOT ENOUGH DATA TO SHOW. PLEASE TRY AGAIN LATER.');
            $('#sentiment-notice').fadeIn(100);
            $('.sentiment-loading').fadeOut(100);
            return;
        }
        if (data !== undefined)
            sentimentData = JSON.parse(data.trim());
        $('#sentiment1, #sentiment2, #sentiment3').show();
        $('.sentiment-loading').fadeOut(100);
        var categories = ['undefined', 'negative', 'neutral', 'possitive'];
        var colors = ['#eee', '#c0504d', '#9bbb59', '#4f81bd'];
        var series = new Array();
        if (count(sentimentData[0]) > 0) {
            var max = sentimentData[0][-2];
            var maxIndex = 0;
            for (j = -2; j <= 1; j++) {
                var i = j + 2;
                var data = {name: categories[i], y: sentimentData[0][j], color: colors[i]};
                series.push(data);
                if (max < sentimentData[0][j]) {
                    max = sentimentData[0][j];
                    maxIndex = i;
                }
            }
            series[maxIndex].sliced = true;
            series[maxIndex].selected = true;
            console.log(series);
            $(function() {
                if ($('#sentiment1').length == 0)
                    return;
                $('#sentiment1').highcharts({
                    chart: {
                        plotBackgroundColor: null,
                        plotBorderWidth: null,
                        plotShadow: false
                    },
                    title: {
                        text: null
                    },
                    tooltip: {
                        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                    },
                    plotOptions: {
                        pie: {
                            allowPointSelect: true,
                            cursor: 'pointer',
                            dataLabels: {
                                enabled: true,
                                color: '#000000',
                                connectorColor: '#000000',
                                format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                            }
                        }
                    },
                    legend: {
                        borderWidth: 0,
                    },
                    series: [{
                            type: 'pie',
                            name: 'Number of mention',
                            data: series
                        }]
                });
            });
        }
        var series2 = [];
        if (count(sentimentData[1]) > 0) {
            var max = sentimentData[1][-2];
            var maxIndex = 0;
            for (j = -2; j <= 1; j++) {
                var i = j + 2;
                var data = {name: categories[i], y: sentimentData[1][j], color: colors[i]};
                series2.push(data);
                if (max < sentimentData[1][j]) {
                    max = sentimentData[1][j];
                    maxIndex = i;
                }
            }
            series2[maxIndex].sliced = true;
            series2[maxIndex].selected = true;
            console.log(series2);
            $(function() {
                if ($('#sentiment2').length == 0)
                    return;
                $('#sentiment2').highcharts({
                    chart: {
                        plotBackgroundColor: null,
                        plotBorderWidth: null,
                        plotShadow: false
                    },
                    title: {
                        text: null
                    },
                    tooltip: {
                        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                    },
                    plotOptions: {
                        pie: {
                            allowPointSelect: true,
                            cursor: 'pointer',
                            dataLabels: {
                                enabled: true,
                                color: '#000000',
                                connectorColor: '#000000',
                                format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                            }
                        }
                    },
                    legend: {
                        borderWidth: 0,
                    },
                    series: [{
                            type: 'pie',
                            name: 'Number of mention',
                            data: series2
                        }]
                });
            });
        }
        var series3 = [];
        if (count(sentimentData[2]) > 0) {
            var max = sentimentData[2][-2];
            var maxIndex = 0;
            for (j = -2; j <= 1; j++) {
                var i = j + 2;
                var data = {name: categories[i], y: sentimentData[2][j], color: colors[i]};
                series3.push(data);
                if (max < sentimentData[2][j]) {
                    max = sentimentData[2][j];
                    maxIndex = i;
                }
            }
            series3[maxIndex].sliced = true;
            series3[maxIndex].selected = true;
            $(function() {
                if ($('#sentiment3').length == 0)
                    return;
                $('#sentiment3').highcharts({
                    chart: {
                        plotBackgroundColor: null,
                        plotBorderWidth: null,
                        plotShadow: false
                    },
                    title: {
                        text: null
                    },
                    tooltip: {
                        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                    },
                    legend: {
                        borderWidth: 0,
                    },
                    plotOptions: {
                        pie: {
                            allowPointSelect: true,
                            cursor: 'pointer',
                            dataLabels: {
                                enabled: true,
                                color: '#000000',
                                connectorColor: '#000000',
                                format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                            }
                        }
                    },
                    series: [{
                            type: 'pie',
                            name: 'Number of mention',
                            data: series3
                        }]
                });
            });
        }
    }

    function count(object) {
        var key, count = 0;
        for (key in object) {
            if (object.hasOwnProperty(key)) {
                count++;
            }
        }
        return count;
    }
    var loadTimer;
    var waitTimer;
    $('.stream-select').change(function() {
        var streamIds = $('.compare-stream-list .stream-select').val();
        if (streamIds !== null) {
            clearTimeout(waitTimer);
            waitTimer = setTimeout(function() {
                loadComparison();
            }, 2000);

            var streamId1 = window.location.href.split('#')[1].split('/')[1];
            var streams = streamIds.join('/');
            var url = "#compare/" + streamId1 + '/' + streams;
            var pl = new SOAPClientParameters();
            pl.add("id", '0');
            pl.add("name", ' ');
            pl.add("streamId1", Base64.decode(streamId1));
            var streamId2 = [];
            for (i = 0; i < streamIds.length; i++) {
                streamId2.push(Base64.decode(streamIds[i]));
            }
            pl.add("streamId2", JSON.stringify(streamId2));
            SOAPClient.invoke("/m", "saveComparison", pl, true, function(r) {
                history.pushState({page: 1}, "Comparison", url);
                $('#compare-link-widget a').attr('href', url);
            });
        }
        else {
            if (SOVRequest !== undefined)
                SOVRequest.abort();
            if (TrendRequest !== undefined)
                TrendRequest.abort();
            if (sentimentRequest !== undefined)
                sentimentRequest.abort();
            $('#sov1, #sov2, #widget-trend, #sentiment1, #sentiment2, #sentiment3, .sov-loading, .trend-loading, .sentiment-loading').hide();
            $('#sov-notice h5, #trend-notice h5, #sentiment-notice h5').html('PLEASE SELECT AT LEAST 1 STREAM TO COMPARE');
            $('#sov-notice, #trend-notice, #sentiment-notice').fadeIn(100);
            sov = undefined;
            trend = undefined;
        }

    });

    function loadComparison() {
        loadSOV(true);
        loadTrend(true);
        loadSentiment(true);
    }

    function clickOnChart(e) {
        console.log(e);
    }

</script>